package webshop.beans.admin;

import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import javax.faces.context.FacesContext;
import javax.imageio.ImageIO;
import javax.servlet.ServletContext;

import org.richfaces.event.UploadEvent;
import org.richfaces.model.UploadItem;

import com.sun.image.codec.jpeg.JPEGEncodeParam;

import database.entity.ShopImage;
import database.entity.ShopItem;
import database.entitymanager.ShopImageManager;
import database.entitymanager.ShopItemManager;
import database.entitymanager.exceptions.NonexistentEntityException;

public class FUBean implements Serializable {

	private static final long serialVersionUID = 1L;

	private List<ShopImage> files;

	private boolean autoUpload;
	private boolean useFlash;
	private ShopImage selectedPicture;
	public static final String contextPath = "C:\\ApacheUploads\\images\\";
	private ShopItem shopItem;
	private int tumbnailHeight = 150;
	private int tumbnailWidth = 150;

	public void init() {
		files = new ArrayList<ShopImage>();
		autoUpload = false;
		useFlash = true;
		File pathFile = new File(contextPath);
		pathFile.mkdirs();

	}

	public FUBean() {
		init();
	}

	public void removePicture() {
		removePicture(selectedPicture);
		files.remove(selectedPicture);
	}

	public boolean removePicture(ShopImage image) {
		File file = new File(contextPath + image.getShopimagerelativepath());
		if (!file.exists())
			return false;
		file.delete();
		if (shopItem.getItemid() != null && image.getShopimageid() != null) {
			try {
				ShopImageManager.destroy(image.getShopimageid());
			} catch (NonexistentEntityException e) {
				e.printStackTrace();
			}
		}
		return true;
	}

	/**
	 * This method copies source file to destination file in console mode.
	 * 
	 * @param source
	 *            - source file to be copied
	 * @param destination
	 *            - destination file to store copy
	 * @throws FileManagerException
	 */
	private static void copyFile(File sourceFile, File destFile) throws Exception {
		try {
			if (destFile.exists()) {
				destFile.delete();
				// return;
			}

			InputStream in = new FileInputStream(sourceFile);
			OutputStream out = new FileOutputStream(destFile);

			byte[] buffer = new byte[1024];

			int length;

			while ((length = in.read(buffer)) > 0) {
				out.write(buffer, 0, length);
			}

			in.close();
			out.close();
		} catch (FileNotFoundException fnfe) {
			throw fnfe;
		} catch (IOException ioe) {
			throw ioe;
		}
	}

	/**
	 * Poziva se kada se file uploaduje.p
	 * 
	 * @param ue
	 */
	public void uploadListener(UploadEvent ue) {
		for (UploadItem ui : ue.getUploadItems()) {
			// UploadItem ui = ue.getUploadItem();
			File f = ui.getFile();

			ShopImage si = new ShopImage();
			// TODO: Morace neka transakcija ili da jednostavno izbrisemo ako ne
			// prodje
			si.setShopimageid(null);
			si.setShopItem(shopItem);
			si.setShopimagename(ui.getFileName());
			si.setShopimagelength(ui.getFileSize());
			si.setShopimagetype(ui.getContentType());
			si.setShopimagerelativepath(String.valueOf(shopItem.getItemid()) + File.separator + ui.getFileName());
			si.setShopimageurl("/image/product/" + shopItem.getItemid() + "/" + (files.size() + 1));

			try {
				File destFolder = new File(contextPath, String.valueOf(shopItem.getItemid()));
				destFolder.mkdirs();
				File destFile = new File(destFolder, si.getShopimagename());

				copyFile(f, destFile);

				f.delete(); // delete temporary file
				files.add(si);
			} catch (Exception e) {
				e.printStackTrace();
				f.delete();
				continue;
			}
		}
	}

	public void clearUploadData() {
		for (ShopImage image : files) {
			removePicture(image);
		}
		files.clear();
	}

	
	
	public void paintTumbnail(OutputStream os, Object obj) {
		ShopItem si = (ShopItem) obj;
		si = ShopItemManager.findShopItem(si.getItemid());
		Image img = null;
		BufferedImage bufImg = null;
		boolean imageFound = false;
		
		for (int i = 0; i < si.getShopImageList().size(); i++) {
			ShopImage shopImage = si.getShopImageList().get(i);
			try {
				img = ImageIO.read(new File(contextPath, shopImage.getShopimagerelativepath()));
				imageFound = true;
			} catch (Exception e) {
				System.err.println("Error in reading image required image! Removing database object and , trying another");
				try {
					ShopImageManager.destroy(shopImage.getShopimageid());
				} catch (NonexistentEntityException e1) {
					System.err.println("Error in deleting ShopImage from FUBean class , paintTumbnail method");
				}
			}
		}
		if (!imageFound) {
			ServletContext ctx = (ServletContext) FacesContext.getCurrentInstance().getExternalContext().getContext();
			String path = ctx.getRealPath("") + File.separator + "img" + File.separator + "no_image.png";
			try {
				img = ImageIO.read(new File(path));
			} catch (IOException e) {
				System.out.println("Error in loading default image! Returning none!");
				return;
			}
		}
		bufImg = new BufferedImage(tumbnailWidth,tumbnailHeight, BufferedImage.TYPE_INT_RGB);
	 
		Graphics2D g2d = bufImg.createGraphics();
		g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION,RenderingHints.VALUE_INTERPOLATION_BILINEAR);
		g2d.drawImage(img, 0, 0, tumbnailWidth , tumbnailHeight, null);
		if (img != null) {
			try {
				ImageIO.write(bufImg, "jpeg", os);
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * Za isrtavanje slike file-a.
	 * 
	 * @param os
	 * @param obj
	 */
	public void paint(OutputStream os, Object obj) {
		ShopImage fb = (ShopImage) obj;
		Image img = null;
		BufferedImage bufImg = null;
		try {
			img = ImageIO.read(new File(contextPath, fb.getShopimagerelativepath()));
			bufImg = new BufferedImage(img.getWidth(null), img.getHeight(null), BufferedImage.TYPE_INT_RGB);
			Graphics2D g2d = bufImg.createGraphics();
			g2d.drawImage(img, 0, 0, null);
		} catch (Exception e) {
			System.err.println("Error in reading image required image! Removing database object and , trying another");
			try {
				ShopImageManager.destroy(fb.getShopimageid());
			} catch (NonexistentEntityException e1) {
				System.err.println("Error in deleting ShopImage from FUBean class , paintTumbnail method");
			}
			return;
		}
		if (img != null) {
			try {
				ImageIO.write(bufImg, "jpeg", os);
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	public List<ShopImage> getFiles() {
		return files;
	}

	public void setFiles(ArrayList<ShopImage> files) {
		this.files = files;
	}

	public boolean isAutoUpload() {
		return autoUpload;
	}

	public void setAutoUpload(boolean autoUpload) {
		this.autoUpload = autoUpload;
	}

	public boolean isUseFlash() {
		return useFlash;
	}

	public void setUseFlash(boolean useFlash) {
		this.useFlash = useFlash;
	}

	public int getSize() {
		return files.size();
	}

	public void setShopItem(ShopItem shopItem) {
		this.shopItem = shopItem;
		files.clear();
		if (shopItem.getItemid() != null) {
			files = shopItem.getShopImageList();
		}
	}

	public ShopItem getShopItem() {
		return shopItem;
	}

	public void setSelectedPicture(ShopImage selectedPicture) {
		this.selectedPicture = selectedPicture;
	}

	public ShopImage getSelectedPicture() {
		return selectedPicture;
	}

	public void setTumbnailHeight(int tumbnailHeight) {
		this.tumbnailHeight = tumbnailHeight;
	}

	public int getTumbnailHeight() {
		return tumbnailHeight;
	}

	public void setTumbnailWidth(int tumbnailWidth) {
		this.tumbnailWidth = tumbnailWidth;
	}

	public int getTumbnailWidth() {
		return tumbnailWidth;
	}
}
